import geopandas as gpd
from geoalchemy2 import Geometry, WKTElement

def shpToPostgis(config,shpFilePath,tableName,schemaName="public"):
    engine = config.engine
    # abc:password对应代表你的用户名和密码，格式为用户名：密码
    # localhost:port就不解释了
    if len(schemaName) ==0:
        schemaName = "public"
    # schemaName='"'+schemaName+'"';
    # 库连接
    conn=config.conn
    cur = conn.cursor()
    cur.execute('CREATE SCHEMA IF NOT EXISTS "' + schemaName+'";')
    # 关闭连接
    conn.commit()
    cur.close()


    # map_data = gpd.GeoDataFrame.from_file('C:/Users/28309/Desktop/01/geopandasShp01.shp')
    # map_data = gpd.read_file(shpFilePath)
    map_data = gpd.GeoDataFrame.from_file(shpFilePath)
    map_data['geom'] = map_data['geometry'].apply(lambda x: WKTElement(x.wkt, 4326))
    geometry_type = map_data['geometry'].type[0]
    map_data.drop(labels='geometry', axis=1, inplace=True)
    # map_data.to_postgis(
    map_data.to_sql(
        # '"'+schemaName+'".'+tableName,
        name=tableName,
        con=engine,
        if_exists='replace',
        schema=str(schemaName),
        index=False,
        dtype={
            'geom': Geometry(geometry_type=geometry_type, srid=4326)
        }
    )
    # # 改字段名称
    # cur = conn.cursor()
    # cur.execute('alter table "'+schemaName+'".'+tableName+' rename column geometry to geom;')
    # # 关闭连接
    # conn.commit()
    # cur.close()

    # 有效性检查
    cur = conn.cursor()
    cur.execute('UPDATE "'+schemaName+'"."'+tableName+'" SET geom = ST_MakeValid (geom) WHERE ST_IsValid (geom) IS FALSE')
    # 关闭连接
    conn.commit()
    cur.close()
    # conn.close()

    print(tableName+'方案计算完成!且已经入库！')
# shpToPostgis(config,r'D:/outdata/demo001.shp','demo001','T20210916')

